<template>
	<div>
		<a-upload :action="action" :before-upload="beforeUploadFC" :disabled="disabled" :file-list="fileListFC"
			list-type="text" @change="handleChangeFC">
			<!--         :customRequest="customRequest || customRequestFC"
       -->
			<div v-if="fileListFC.length < maxFileLength && !disabled">
				<a-button> <a-icon type="upload" />
					<slot>上传附件</slot>
				</a-button>
			</div>
			<div style="margin: 10px 2px;" v-if="accept">
				<span style="color: red;">*</span> 上传格式支持 {{ acceptTip }} 格式文件
			</div>
		</a-upload>
		<!-- <a-modal :visible="previewVisible" :footer="null" @cancel="handlePreviewCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal> -->
	</div>
</template>
<script>
import { sysFileInfoUpload } from '@/api/modular/system/fileManage'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
	name: 'fc-upload',
	props: {
		// ----------------------修改apiTest---------------------
		action: {
			type: String,
			default: `/api/sysFileInfo/upload`
		},
		maxFileLength: {
			type: Number,
			default: 8
		},
		accept: {
			type: String,
			default: null
		},
		fileList: {
			type: Array,
			default: function () {
				return []
			}
		},
		beforeUpload: {},
		handleFileListChange: {},
		handleFileListStringChange: {},
		disabled: false
	},
	data() {
		return {
			fileListFC: [...this.fileList],
			// previewVisible: false,
			// previewImage: ''
		}
	},
	computed: {
		fileListString() {
			return this.fileListFC.filter(f => f.status === 'done').map(f => f.fileID).join(',')
		},
		acceptTip() {
			return this.accept.split(",").join("/")
		}
	},
	created(){
		// console.log(this.$store.state.baseUrl);
		
		// this.action = `${this.$store.state.baseUrl}/sysFileInfo/upload`
	},
	watch: {
		fileList() {
			this.fileListFC = [...this.fileList]
		}
	},
	methods: {
		beforeUploadFC(file) {
			console.log('文件数据', file)

			const pblength = this.fileListFC.length == 0
			console.log('999999', pblength)
			if (!pblength) {
				this.$message.error("只可上传一个附件！")
			}
			let isTypeOk = false;
			if (this.accept) {
				let fileExtension = '';
				if (file.name.lastIndexOf('.') > -1) {
					fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
				}
				console.log(fileExtension);
				
				isTypeOk = this.accept.split(",").some((type) => {
					if (file.type.indexOf(type) > -1) return true;
					if (fileExtension && fileExtension.indexOf(type) > -1) return true;
					return false;
				});
				if (!isTypeOk) {
					this.$message.error(
						`文件格式不正确, 请上传${this.acceptTip.split(",").join('/')}格式文件!`
					);
					return false;
				}

			}
			// const isJpgOrPng = (file.type === 'application/pdf' ||
			// 	file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
			// 	file.type === 'image/jpeg' || file.type === 'image/png')
			// if (!isJpgOrPng) {
			// 	this.$message.error('只能上传PDF/DOC/DOCX/JPG/PNG类型文件!')
			// }
			// const isLt2M = file.size / 1024 / 1024 < 20
			// if (!isLt2M) {
			// 	this.$message.error('文件大小必须小于20MB!')
			// }
			// return pblength && isJpgOrPng && isLt2M
			return pblength && isTypeOk
		},
		handleChangeFC(event) {
			// TODO 看了源码,懂了一点.不重写上传方法也没问题.当上传成功时,可以从event.file.response 中 获取到服务器返回内容
			let { file, fileList } = event

			this.fileListFC = fileList
			// 如果在上传前判断格式或大小不符合，将不会进行自动上传。这处的状态为undefined
			if (file.status === undefined) {
				fileList.pop()
			}

			// 只有当成功上传或删除时,才调用父级的变动方法
			if (file.status === 'done') {
				// 由于file和FileList中的对象不是同一个,所以需要找到受控的对象,再加添属性
				let findFile = fileList.find(f => f.uid == file.uid)
				// 服务端响应内容
				let response = findFile.response
				findFile.fileID = response.data
			}

			if (file.status === 'done' || file.status === 'removed') {
				if (this.handleFileListChange) {
					this.handleFileListChange(fileList)
				}
				if (this.handleFileListStringChange) {
					this.handleFileListStringChange(this.fileListString)
				}
				this.$emit('change', this.fileListString)
			}
		},
		// customRequestFC(data) {
		//   const formData = new FormData()
		//   formData.append('file', data.file)
		//   sysFileInfoUpload(formData).then((res) => {
		//     if (res.success) {
		//       this.$message.success('上传成功')
		//
		//       const token = Vue.ls.get(ACCESS_TOKEN)
		//
		//       let _fl = this.fileListFC
		//       let lastFile = _fl[_fl.length - 1]
		//       let imageUrl = `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${res.data}&token=${token}`
		//       // 为了节省流量，上传成功的图片预览图直接使用文件的thumbUrl
		//       imageUrl = lastFile.thumbUrl
		//       lastFile.fileID = res.data
		//       lastFile.url = imageUrl
		//       lastFile.status = 'done'
		//
		//       this.$emit('change', data.file, _fl);
		//
		//       if (this.afterUpload) {
		//         this.afterUpload(true, res, this.fileListFC)
		//       }
		//       if (this.afterHandleChange) {
		//         this.afterHandleChange(this.fileListFC)
		//       }
		//     } else {
		//       this.$message.error('上传失败：' + res.message)
		//       this.$emit('change', data.file, this.fileListFC);
		//
		//       this.fileListFC.pop()
		//       if (this.afterHandleChange) {
		//         this.afterHandleChange(this.fileListFC)
		//       }
		//       if (this.afterUpload) {
		//         this.afterUpload(false, res, res.message)
		//       }
		//     }
		//   }).catch(reason => {
		//     console.error(`sysFileInfoUpload error:${reason}`)
		//     this.$emit('change', data.file, this.fileListFC);
		//     this.fileListFC.pop()
		//     if (this.afterHandleChange) {
		//       this.afterHandleChange(this.fileListFC)
		//     }
		//     if (this.afterUpload) {
		//       this.afterUpload(false, null, reason)
		//     }
		//   })
		// },
		// async handlePreviewFC(file) {
		//   this.previewImage = file.url || file.preview || `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${file.fileID}` 
		//   this.previewVisible = true
		// },
		// handlePreviewCancel() {
		//   this.previewVisible = false
		// },
		handleClear() {
			this.fileListFC = []
		}
	}
}
</script>